package com.qfedu.aunt.commons.interceptor;

import com.qfedu.aunt.commons.exception.BusinessException;
import com.qfedu.aunt.commons.result.R;
import com.qfedu.aunt.commons.result.ResponseCode;
import com.qfedu.aunt.commons.slot.base.SlotChain;
import com.qfedu.aunt.commons.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: GlobleInterceptor
 * @projectName aunt_commons_2209
 * @description: TODO
 * @date 2022/11/4  15:40
 */
@Component
public class GlobleInterceptor implements HandlerInterceptor {

    @Autowired
    private SlotChain slotChain;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            slotChain.dealReq(request);
            //程序执行到这里 如果都没错 那么说明整个代码 刚刚的
            return true;
        }catch (Exception err){
            //这里还要说明出错的原因在哪里?
            if(err instanceof BusinessException){
                //说明是可预期的异常
                BusinessException bs= (BusinessException) err;
                ResponseUtils.out(response, R.error(bs.getCode(),bs.getMessage()));
            }else{
                //不可预期的异常
                ResponseUtils.out(response, R.error(
                        ResponseCode.SYSTEM_ERROR.getCode(),
                        ResponseCode.SYSTEM_ERROR.getMessage()));
            }
            //说明出错了
            return false;
        }


    }
}
